package vooga.entities;

import java.util.HashMap;
import java.util.HashSet;

/**
 * manages a collection of entities tagged with String group ids
 * @author Congyi Wu
 *
 */
public class EntitySet implements Iterable<Entity>{
	private java.util.HashSet<Entity> myEntities;
	private java.util.HashMap<String, java.util.HashSet<Entity>> myEntitiesByGroup;
		
	public EntitySet()
	{
		myEntities = new HashSet<Entity>();
		myEntitiesByGroup = new HashMap<String, HashSet<Entity>>();
	}
	
	/**
	 * add entity to default group
	 * @param e
	 */
	public void add(Entity e)
	{
		myEntities.add(e);
		for(String g : e.getGroups())
		{
			if(!myEntitiesByGroup.containsKey(g))
				myEntitiesByGroup.put(g, new HashSet<Entity>());
			myEntitiesByGroup.get(g).add(e);
		}
	}

	public void addAll(java.util.Collection<? extends Entity> entities)
	{
		for(Entity e: entities)
			add(e);
	}
	
	/**
	 * 
	 * @param group
	 * @return set of Entities of group group
	 */
	public java.util.HashSet<Entity> get(String group)
	{
		return myEntitiesByGroup.get(group);
	}

	public Entity getFirst(String group)
	{
		java.util.HashSet<Entity> temp = myEntitiesByGroup.get(group);
		if(temp == null ||temp.isEmpty())
			return null;
		return temp.iterator().next();
	}
	
	public void remove(Entity e)
	{
		myEntities.remove(e);
		for(String g : e.getGroups())
		{
			if(myEntitiesByGroup.containsKey(g))
			{
				HashSet<Entity> currGroup = myEntitiesByGroup.get(g);
				currGroup.remove(e);
				if(currGroup.isEmpty())
					myEntitiesByGroup.remove(g);
			}
		}
	}

	public java.util.Iterator<Entity> iterator() {
		return myEntities.iterator();
	}
}